-- UIPetCampCard
-- Created by huanghr Nov/15/2016
-- 购买佣兵营地月卡界面

UIPetCampCard = class("UIPetCampCard", function()
    return cc.Layer:create();
end);

function UIPetCampCard.create()
    return UIPetCampCard.new();
end

-- 奖励显示项（固定5个排成一行）
local ITEM_NUMBER = 5;

-- 阵营系列
local CAMP_LIST = {2, 1, 3, 4};

-- 构造函数
function UIPetCampCard:ctor()
    self:setName("UIPetCampCard");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/market/SuperiorBonusTip.csb");
    self:addChild(node);
    self.node = node;

    self.goodsId = FormulaM.invoke("GET_PET_CAMP_CARD_GOODSID");

    -- 参数
    self:initDesc();

    self:setLocalZOrder(UIMgr.BONUS_NOTIFY_ZORDER + 1);

    -- 注册点击事件
    self:registerTouchEvent();

    -- 注册事件回调
    self:registerEventCallback();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize(node);
end

-- 编辑当前所有文本
function UIPetCampCard:initDesc()
    local goodsInfo = MarketM.getGoodsInfo(self.goodsId);
    local goodName = goodsInfo["name"];
    local desc = goodsInfo["confirm"];

    local sku = MarketM.querySku(self.goodsId);
    local price;
    if type(sku) ~= 'string' then
        price = string.format("$%.2f", table.values(goodsInfo["price"])[1]);
    else
        price = MarketM.getPriceBySku(sku);
    end

    -- 转换美元
    changeDollerCharacter(price);

    self.title = goodName;
    self.desc = MarketM.parseGoodsDesc(desc, goodsInfo);

    -- 超值额度，这个策划给定的
    self.value = 866;

    self.okText = string.format(getLocStr("btn_text_buy_with_price"), price);
end

-- 注册事件回调
function UIPetCampCard:registerEventCallback()
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UIPetCampCard 界面析构清理");
            EventMgr.removeAll("UIPetCampCard");
        elseif eventType == "enter" then
        end
    end);
end

-- 注册点击事件
function UIPetCampCard:registerTouchEvent()
    local BT = findChildByName(self.node, "BT");

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(BT, "btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIPetCampCard");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);

    -- 注册确定按钮点击事件
    local btnOk = findChildByName(self.node, "CT/btn_ok");
    local function onOkClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            self:doBuy();
        end
    end
    btnOk:addTouchEventListener(onOkClick);
end

-- 适配
function UIPetCampCard:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 重绘
function UIPetCampCard:redraw()
    -- 设置返回按钮的文本样式
    local btnBack = findChildByName(self.node, "BT/btn_back");
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 设置确认按钮文本样式
    local btnOk = findChildByName(self.node, "CT/btn_ok");
    local btnText = self.okText or getLocStr("btn_text_ok");

    -- 美元符号修改
    btnText = changeDollerCharacter(btnText);

    TextStyleM.setTextStyle(btnOk, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnOk:setTitleText(btnText);

    -- 重绘奖励容器
    self:redrawBonus();

    -- 标题
    local titleNode = findChildByName(self.node, "CT/title_node");
    local descLabel = findChildByName(self.node, "CT/desc");
    local valueNode = findChildByName(self.node, "CT/value_node");
    local btnOk = findChildByName(self.node, "CT/btn_ok");
    local titleLabel = findChildByName(titleNode, "title");
    local subHead = findChildByName(titleNode, "subhead");
    local valueDesc = findChildByName(valueNode, "desc");
    local valueLabel = findChildByName(valueNode, "value");
    local icon = findChildByName(valueNode, "icon");
    local btnDiscount = findChildByName(self.node, "CT/btn_discount");
    local btnOriginal = findChildByName(self.node, "CT/btn_original");
    local valueBg = findChildByName(self.node, "CT/value_bg");

    -- 标题
    titleLabel:setString(self.title);
    TextStyleM.setArtWordTitleStyle(titleLabel);

    -- 描述
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    descLabel:setString(self.desc);
    descLabel = applyString(descLabel, self.desc);

    -- 价值
    valueDesc:setString(getLocStr("bonus_value_desc"));

    TextStyleM.setTextStyle(valueLabel, TextStyleM.TEXT_SIZE_LARGE2, TextStyleM.TEXT_COLOR_ORANGE, true, nil, nil, nil, nil, nil, true);
    TextStyleM.setTextStyle(valueDesc, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_ORANGE, true, nil, nil, nil, nil, nil, true);

    valueLabel:setString(string.format(getLocStr("percent"), self.value));

    -- 显示ICON
    icon:setVisible(false);

    -- 设置超值额度底图
    valueBg:setOpacity(200);
    valueBg:setScale(1.2);
    valueBg:setPositionX(valueBg:getPositionX() - 15);

    -- 自适应
    local bonusPanel = findChildByName(self.node, "CT/bonus_panel1");
    local bonusPanel2 = findChildByName(self.node, "CT/bonus_panel2");
    local bg = findChildByName(self.node, "CT/bg");

    local nodeArr = { descLabel, bonusPanel, valueBg, btnOk, btnDiscount};
    local offsetArr = { 35, };

    AlignM.adaptLayout(bg, AlignM.BG_SIZE_COMMON, nodeArr, offsetArr, 100);

    -- 计算标题新位置
    local bgScale = bg:getScaleY();
    local bgHeight = getRealContentSize(bg).height;
    local newPosY = titleNode:getPositionY() * bgScale;
    titleNode:setPositionY(newPosY);

    -- 计算超值额度的位置
    valueDesc:setPosition(valueDesc:getPositionX() + 30, valueBg:getPositionY() + 60);
    if not isFullWidthLang() then
        valueLabel:setPosition(valueLabel:getPositionX(), valueDesc:getPositionY() - 38);
    else
        valueLabel:setPosition(valueLabel:getPositionX() + 30, valueDesc:getPositionY() - 38);
    end

    -- 设置原价按钮的位置
    btnOriginal:setPositionY(btnDiscount:getPositionY());
end

-- 重绘奖励容器
function UIPetCampCard:redrawBonus()
    local bonusList = self.bonusList or {};
    local parentNode = findChildByName(self.node, "CT/bonus_panel1/bonus_node");
    local parentNode2 = findChildByName(self.node, "CT/bonus_panel2/bonus_node");

    -- 先清空
    parentNode:removeAllChildren();
    parentNode2:removeAllChildren();

    local item = cc.CSLoader:createNode("layout/common/CommonItem.csb");
    item = replaceNodeWithWidget(item);

    local itemWidth = 100;

    -- 计算下奖励
    local bonusList = FormulaM.invoke("PET_CAMP_CARD_BONUS");

    for i = 1, ITEM_NUMBER do
        local itemNode = item:clone();

        itemNode:setScale(0.8);
        local icon = findChildByName(itemNode, "icon");
        local tipImg = findChildByName(itemNode, "tip");
        local desc = findChildByName(itemNode, "desc");
        desc:setVisible(false);
        local iconPath;
        if i == 1 then
            -- 固定为奖励（当前只有一种奖励）
            -- 如果有多个奖励优先取第一个
            local bonus;

            if type(bonusList[1]) == "table"then
                bonus = bonusList[1];
            else
                bonus = bonusList;
            end

            tipImg:setVisible(false);
            desc:setVisible(true);
            TextStyleM.setTextStyle(desc, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
            desc:setString("+" .. bonus[3]);

            if bonus[1] == 1 then
                local path = ItemM.query(bonus[2], "icon");
                iconPath = getItemIconPath(bonus[2]);
            elseif bonus[1] == 2 then
                local path = FieldsM.query(bonus[2], "icon");
                iconPath = getLargeAttribIconPath(path);
            else
                -- 其他暂不处理(给个默认的物品图标)
                iconPath = getItemIconPath(1);
            end
        else
            iconPath = getCampIconPath2(CAMP_LIST[i - 1]);

            tipImg:loadTexture(getCornerImg("daily_bonus"));
            tipImg:setVisible(true);
        end

        icon:loadTexture(iconPath);

        local x = (i - 1) * itemWidth + 50 - 250;
        itemNode:setPosition(x, 0);

        parentNode:addChild(itemNode);
    end
end

-- 购买佣兵营地月卡
function UIPetCampCard:doBuy()
    -- 先通过统一接口判断下能不能购买
    local ret = MarketM.canBuyGoods(self.goodsId)
    if true ~= ret or type(ret) == "string" then
        if "sold_out" == ret then
            -- 该商品已售完
            alert(string.format(getLocStr("market_goods_sold_out"), MarketM.query(goodsId, "name")));
        elseif "gem_lack" == ret then
            -- 钻石不足
            showGemLackConfirm();
        elseif type(ret) == "string" then
            -- 有提示语，提示之
            alert(getLocStr(ret));
        else
            -- 其他原因，统一提示失败
            trace("UIMarketMain", "购买失败，原因：" .. tostring(ret))
            alert(getLocStr("market_buy_fail"));
        end

        -- 关闭界面
        UIMgr.getCurrentScene():removeFormByName("UIPetCampCard");
        return;
    end

    -- 如果在手机上，通过sdk购买（pt购买不限手机平台）
    if isAndroidPlatform() or isIosPlatform() or MarketM.isBuyGemByPt() then
        if MarketM.isInlandPayWay() then
            showInlandPayWay(self.goodsId);
        else
            MarketM.buyByRmb(self.goodsId);
        end
    else
        -- 暂未开放
        alert(getLocStr("disable_function"));
    end

    -- 关闭界面
    UIMgr.getCurrentScene():removeFormByName("UIPetCampCard");
end